﻿using System;
using System.Diagnostics;
using System.IO;
using Microsoft.SharePoint;

namespace DE.Sdc.SharePoint.ContentStructureDemoReceiver
{
    public class FeatureReceiver : SPFeatureReceiver
    {

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            base.FeatureActivated(properties);

            SPSite site = properties.Feature.Parent as SPSite;
            if (site == null)
            {
                var web = properties.Feature.Parent as SPWeb;
                if (web != null)
                    site = web.Site;
            }

            if (site != null)
            {                
                string contentStructureXmlPath = GetFeatureReceiverPropertyValue(properties, "ContentStructureXmlPath");
                if (!string.IsNullOrEmpty(contentStructureXmlPath))
                {
                    string[] split = contentStructureXmlPath.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string path in split)
                    {
                        ImportContentStructure(properties, path);
                    }
                }
            }
        }

        private static void ImportContentStructure(SPFeatureReceiverProperties properties, string contentStructureXmlPath)
        {
            try
            {
                Trace.WriteLine(">>> ContentStructure wird importiert");
                if (!Path.IsPathRooted(contentStructureXmlPath))
                    contentStructureXmlPath = Path.Combine(properties.Definition.RootDirectory, contentStructureXmlPath);
                SPContentStructure.Import.SPContentStructureImport.Import(contentStructureXmlPath, properties);
                Trace.WriteLine(">>> Das Aktivieren war erfolgreich.");
            }
            catch (Exception)
            {
                Trace.WriteLine(">>> Das Aktivieren war nicht erfolgreich.");
                throw;
            }
        }

        private static string GetFeatureReceiverPropertyValue(SPFeatureReceiverProperties properties, string propertyName)
        {
            try
            {
                return properties.Definition.Properties[propertyName].Value;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
